# -*- coding: utf-8 -*-
import csv
import os
from obs import ObsClient, PutObjectHeader

from sdk.project import Project


def backup(client):
    repos = client.repositories()
    for repo in repos:
        os.system('git clone --mirror ' + repo.sshUrl)


def move_repo(client, url, prj_name, repo_name):
    print("move repo to "+prj_name+"/"+repo_name)
    os.system('git clone --mirror ' + url)
    prj = client.find_project_by_name(prj_name)
    if prj == None:
        prj = client.create_project_by_name(prj_name)
    repo = prj.find_repo_by_name(repo_name)
    if repo == None:
        repo = prj.create_repo_by_name(repo_name)
    repo_path = url.split("/")[-1]
    os.chdir(repo_path)
    os.system('git remote add upload ' + repo.sshUrl)
    os.system('git push -f upload --all')
    os.chdir('..')

def move(client, file_path):
    print("start move")
    with open(file_path) as f:
        render = csv.reader(f)
        for row in render:
            url = row[0]
            prj_name = row[1]
            repo_name = row[2]
            move_repo(client, url, prj_name, repo_name)


def restore(client):
    print("敬请期待")

def display(client):
    repos = client.repositories()
    for repo in repos:
        prj = Project.find_by_uuid(client.client, repo.projectUuid)
        print(prj.name + "/" + repo.name + "    url:  " + repo.sshUrl)

def download(file_path, repoPath):
    print(repoPath)    
    with open(file_path) as f:
        render = csv.reader(f)
        for row in render:
            print("download repo : " + row[0])
            os.chdir(repoPath)
            os.system('git clone --mirror ' + row[0])
            dirName = row[0].split("/")[-1]
            os.system('tar czvf ' + dirName +".tar.gz " + dirName)


def uploadRepo(bucketClient, key, file_path):
    Lheaders = PutObjectHeader(md5=None, acl='private', location=None, contentType='application/gzip')
    Lmetadata = {'key': 'value'}
    resp = bucketClient.putFile(objectKey=key, file_path=file_path,
                                metadata=Lmetadata, headers=Lheaders)
    if isinstance(resp, list):
        for k, v in resp:
            print('objectKey', k, 'common msg:status:', v.status, ',errorCode:', v.errorCode, ',errorMessage:',
                  v.errorMessage)
    else:
        if resp.status==200 :
            print("upload file : " + file_path)        

def uploadRepos(ak, sk, server, bucketName, repoPath):
    obsClient = ObsClient(access_key_id=ak, secret_access_key=sk, server=server)
    bucketClient = obsClient.bucketClient(bucketName)
    for root, dirs, files in os.walk(repoPath):
        for name in files:
            names = name.split(".")
            if len(names)>2 :
                if names[-1]=="gz" :
                    uploadRepo(bucketClient, name, repoPath +"/"+ name)